/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shuyihui.rxhttp.interceptor

import com.shuyihui.rxhttp.model.HttpHeaders
import com.shuyihui.rxhttp.utils.HttpLog
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 *
 * 描述：配置公共头部
 */
class HeadersInterceptor(private val headers: HttpHeaders) : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val builder: Request.Builder = chain.request().newBuilder()
        if (headers.headersMap?.isEmpty() == true) return chain.proceed(builder.build())
        try {
            for ((key, value) in headers.headersMap!!) {
                //去除重复的header
                //builder.removeHeader(entry.getKey());
                //builder.addHeader(entry.getKey(), entry.getValue()).build();
                builder.header(key, value).build()
            }
        } catch (e: Exception) {
            HttpLog.e(e)
        }
        return chain.proceed(builder.build())
    }
}